package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.DNReformAdapter;
import com.example.administrator.yanfoxconn.bean.DNReform;
import com.example.administrator.yanfoxconn.bean.DNSpinner;
import com.example.administrator.yanfoxconn.bean.KOInfo;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.example.administrator.yanfoxconn.widget.SwipeListViewOne;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Song
 * on 2021/12/06
 * Description：安保部 臨時來訪 列表界面
 */
public class KOListActivity extends BaseActivity implements View.OnClickListener {
    private final int MESSAGE_SET_LIST = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_SET_SEARCH_LIST = 3;//提交信息回復
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_BUILDING = 6;//棟
    private final int MESSAGE_SET_FLOOR = 7;//層
    private final int MESSAGE_SET_ROOM = 8;//房間


    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題

    @BindView(R.id.ll_tr)
    LinearLayout llTR;//查詢條件部分
    @BindView(R.id.et_name)
    EditText etName;//姓名
    @BindView(R.id.et_car)
    EditText etCar;//車牌號
    @BindView(R.id.btn_check)
    Button btnCheck;//查詢
    @BindView(R.id.lv_one)
    SwipeListViewOne listView;
    @BindView(R.id.lv_normal)
    MyListView lvNormal;

    private DNReformAdapter dnReformAdapter;
    private List<KOInfo> koInfoList,koSearchList;

    private String from;//來源，all顯示條件查詢，全部異常；self不顯示條件查詢，屋內異常
    private Date curDate = null;//當前時間
    private SimpleDateFormat formatter;
    private String outTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ko_lv);
        ButterKnife.bind(this);
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        outTime = formatter.format(curDate);
        tvTitle.setText(getIntent().getStringExtra("title"));
        btnBack.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        from = getIntent().getStringExtra("from");
        if (from.equals("list")) {
            getAllListHandler("list");
            llTR.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
        }else if (from.equals("search")){
            listView.setVisibility(View.GONE);
            llTR.setVisibility(View.VISIBLE);
        }
//        if (reformList != null) {
////            setListViewHeightBasedOnChildren(listView);
//            clickSeeOrAdd();
//        }
    }

    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     *
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        DNReformAdapter listAdapter = (DNReformAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    private void clickSeeOrAdd() {
        dnReformAdapter.setOnClickListenerSeeOrAdd(new DNReformAdapter.OnClickListenerSeeOrAdd() {
            @Override
            public void OnClickListenerSee(int position) {
                leave(koInfoList.get(position).getID(),outTime,"leave");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_check://查詢
                getSearch(etName.getText().toString(),etCar.getText().toString(),"search");
                break;
        }
    }



    private String url2 = "";

    private void getAllListHandler(String flag){
url2=Constants.HTTP_KO_LIST + "?flag="+flag;
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        koInfoList = new ArrayList<KOInfo>();

                        for (JsonElement type : array) {
                            KOInfo humi = gson.fromJson(type, KOInfo.class);
                            koInfoList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    //臨時來訪出場 flag：leave
    private void leave(String id,String out_time,String flag){
        try {
            String outTime =  URLEncoder.encode(URLEncoder.encode(out_time.toString(), "UTF-8"), "UTF-8");
            String m_out_guard_name1 =  URLEncoder.encode(URLEncoder.encode(FoxContext.getInstance().getName(), "UTF-8"), "UTF-8");

            url2=Constants.HTTP_KO_LIST + "?flag="+flag+"&id="+id+"&out_time="+outTime+"&m_out_guard="+FoxContext.getInstance().getLoginId()+"&m_out_guard_name="+m_out_guard_name1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errCode").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void getSearch(String c_name,String c_car,String flag){
        try {
            String c_name1 =  URLEncoder.encode(URLEncoder.encode(c_name.toString(), "UTF-8"), "UTF-8");
            String c_car1 =  URLEncoder.encode(URLEncoder.encode(c_car.toString(), "UTF-8"), "UTF-8");

            url2=Constants.HTTP_KO_LIST + "?flag="+flag+"&c_name="+c_name1+"&c_car="+c_car1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        koSearchList = new ArrayList<KOInfo>();

                        for (JsonElement type : array) {
                            KOInfo humi = gson.fromJson(type, KOInfo.class);
                            koSearchList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_SEARCH_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    if (msg.obj.toString().equals("200")){
                        getAllListHandler("list");
                    }else{
                        aboutAlert(msg.obj.toString(), MESSAGE_TOAST);
                    }
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(KOListActivity.this, R.string.net_mistake);
                    break;
                case MESSAGE_SET_LIST://進度賦值
                    dnReformAdapter = new DNReformAdapter(KOListActivity.this, koInfoList, "KO");
                    listView.setAdapter(dnReformAdapter);
                    setListViewHeightBasedOnChildren(listView);
                    clickSeeOrAdd();
                    break;
                case MESSAGE_SET_SEARCH_LIST://樓棟賦值
                    dnReformAdapter = new DNReformAdapter(KOListActivity.this, koSearchList, "KO","search");
                    lvNormal.setAdapter(dnReformAdapter);
                    setListViewHeightBasedOnChildren(lvNormal);
                    break;
//                case MESSAGE_SET_FLOOR://樓層賦值
//                    setFloor();
//                    break;
//                case MESSAGE_SET_ROOM://區域賦值
//                    setRoom();
//                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type == MESSAGE_TOAST) {
                            if (koInfoList != null) {
                                koInfoList.clear();
                                dnReformAdapter = new DNReformAdapter(KOListActivity.this, koInfoList,"KO");
                                listView.setAdapter(dnReformAdapter);
                            }
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//        if (from.equals("self")) {
//            getList();
//        } else if (building.equals("") || floor.equals("")) {
//            getArea();
//        }else{
//            getList();
//        }
//    }
}